using System;
using System.ComponentModel;

namespace Programonica.Igramonica.Core
{
    public delegate void Command();

    public class BackgroundHandler
    {
        private readonly Command m_callback;

        private readonly Command m_command;

        public BackgroundHandler(Command command, Command callback)
        {
            m_command = command;

            m_callback = callback;
        }

        public void ExecuteOperation()
        {
            BackgroundWorker backgroundWorker = new BackgroundWorker();

            backgroundWorker.DoWork += backgroundWorker_DoWork;

            backgroundWorker.RunWorkerCompleted += backgroundWorker_RunWorkerCompleted;

            backgroundWorker.RunWorkerAsync();
        }

        private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                throw e.Error;
            }

            if (m_callback != null)
            {
                m_callback();
            }
        }

        private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            if (m_command != null)
            {
                m_command();
            }
        }
    }
}